import importlib.util
import inspect
import typing
from tkinter import *
from tkinter import ttk

from simulators.mumu_control import MuMuControl
from ui_engine.components import LoginDialog
from ui_engine.tabs import ConfigTab, LogAreaTab, SimulatorTab, MainPanel, UpdateTab, ChatArea
from ui_engine.task_manager import task_manager
from ui_engine.tasks import AttackTask
from utils.utils import account_config, EventBus, CommonUtils

account = account_config()["account"]


class LeUi:

    def __init__(self, simulator_control: MuMuControl):
        self.is_destroy = False
        self.root = Tk()
        self.root.protocol("WM_DELETE_WINDOW", self.destroy_win)
        self.root.resizable(False, True)
        self.center_window()
        self.root.title("Little Empire")
        self.set_icon()
        self.sim_ctl = simulator_control

        self.event_bus = EventBus()

        self.task_list: typing.List[AttackTask] = []
        self.create()

    @staticmethod
    def get_task_map() -> dict:
        module = importlib.import_module("ui_engine.tasks")

        # 获取所有类（仅限模块定义的类）
        classes = {
            getattr(obj, "TASK_NAME", "COMMON"): obj for name, obj in inspect.getmembers(module, inspect.isclass)
            if getattr(obj, "TASK_NAME", "COMMON") != "COMMON"
        }
        return classes

    def create(self):
        login = LoginDialog(self.root)
        if login.get_result():
            self.create_tabs()
        else:
            self.destroy_win()

    def create_tabs(self):

        top_frame = Frame(self.root)
        top_frame.pack(fill=BOTH, expand=True)

        style = ttk.Style()
        style.configure("TNotebook.Tab", padding=[12, 6], font=('SimSun', 10, "bold"), foreground="black")
        style.map("TNotebook.Tab", background=[("selected", "#f0f0f0")])

        notebook = ttk.Notebook(top_frame)
        notebook.pack(fill='both', expand=True)
        notebook.bind("<<NotebookTabChanged>>", self.on_tab_changed)
        self.notebook = notebook

        config_tab = ConfigTab(notebook, e=self.event_bus)
        notebook.add(config_tab, text="用户配置")

        simulator_tab = SimulatorTab(notebook, simulator_control=self.sim_ctl, e=self.event_bus)
        notebook.add(simulator_tab, text="模拟器管理")

        main_panel = MainPanel(notebook, config_tab, simulator_tab, self.get_task_map, e=self.event_bus)
        notebook.add(main_panel, text="任务面板")

        chat_panel = ChatArea(notebook)
        notebook.add(chat_panel, text="SmartPlayer")
        self.chat_panel = chat_panel

        update_tab = UpdateTab(notebook)
        notebook.add(update_tab, text="更新日志")

        bottom_frame = Frame(self.root, height=300)
        bottom_frame.pack(fill=X)
        self.bottom_frame = bottom_frame

        log_tab = LogAreaTab(bottom_frame)
        log_tab.pack(fill=BOTH, expand=True)

    # 绑定 tab 切换事件
    def on_tab_changed(self, event):
        selected = self.notebook.nametowidget(self.notebook.select())  # 当前显示的 tab widget
        if selected == self.chat_panel:
            self.bottom_frame.pack_forget()  # 隐藏日志区
        else:
            self.bottom_frame.pack(fill=X)  # 显示日志区

    def destroy_win(self):

        task_manager.shutdown()

        if not self.is_destroy:
            self.root.destroy()
            self.is_destroy = True

    def set_icon(self):
        # 加载PNG图像并转换为ICO格式
        self.root.iconphoto(False, PhotoImage(file=CommonUtils.resource_path(["resource", "icon_cleaned.png"])))

    def center_window(self, width=800, height=700):
        # 获取屏幕宽高
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()

        # 计算窗口左上角坐标
        x = (screen_width - width) // 2
        y = (screen_height - height) // 2

        # 设置窗口尺寸和位置
        self.root.geometry(f"{width}x{height}+{x}+{y}")

    def show(self):
        self.root.mainloop()